from flask import Blueprint, render_template, request, jsonify, redirect,url_for,session
from flask_mail import Message
from exts import ma, db
import random
import string
from models import EmailCaptchaModel, UserModel
from .forms import RegisterForm, LoginForm
from werkzeug.security import generate_password_hash,check_password_hash
aubp = Blueprint('auth', __name__, url_prefix='/auth')


@aubp.route('/login',methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        form = LoginForm(request.form)
        if form.validate():
            email = form.email.data
            password = form.password.data
            user = UserModel.query.filter_by(email=email).first()
            if user and check_password_hash(user.password, password):
                session['user_id'] = user.id
                return redirect(url_for('qa.index'))
            else:
                return redirect(url_for('auth.login'))
        else:
            print(form.errors)
            return redirect(url_for('auth.register'))

    return render_template('login.html')


@aubp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template('register.html')
    else:
        form = RegisterForm(request.form)
        if form.validate():
            email= form.email.data
            username = form.username.data
            password = form.password.data
            user = UserModel(email=email, username=username, password=generate_password_hash(password))
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('auth.login'))

        else:
            print(form.errors)
            return redirect(url_for('auth.register'))



@aubp.route('/mail/test')
def mail_test():
    message = Message('测试邮件标题', recipients=['714716839@qq.com', '1067750224@qq.com'],
                      body='这是一封测试邮件，发送给初一')
    # mail.send_message(
    #     subject='测试邮件',
    #     recipients=['',''],
    #     body='这是测试邮件'
    # )
    ma.send(message)
    return '发送成功'


@aubp.route('/captcha/email')
def auth_captcha():
    email = request.args.get('email')
    captchalist = random.sample(string.ascii_letters + string.digits, 4)
    captcha = ''.join(captchalist)
    message = Message('验证码发送', recipients=[email], body=f'您好，您收到的验证码是：{captcha}')
    ma.send(message)
    email_captacha = EmailCaptchaModel(email=email, captcha=captcha)
    db.session.add(email_captacha)
    db.session.commit()
    return jsonify({"code": 200, "message": "", "data": None})


@aubp.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('qa.index'))
